package cn.yuanqiao.archive.guidang.service.impl;

import cn.yuanqiao.archive.appManager.domain.TenantCategory;
import cn.yuanqiao.archive.appManager.domain.TenantYqdaDocument;
import cn.yuanqiao.archive.appManager.mapper.TenantCategoryMapper;
import cn.yuanqiao.archive.appManager.mapper.TenantYqdaDocumentMapper;
import cn.yuanqiao.archive.appManager.service.ITenantSysConfigService;
import cn.yuanqiao.archive.chengguojieshou.mapper.YqdaarticulatedMapper;
import cn.yuanqiao.archive.guidang.ArchiveOfOfficialDocument;
import cn.yuanqiao.archive.guidang.domain.Guidangpackage;
import cn.yuanqiao.archive.guidang.enums.Case;
import cn.yuanqiao.archive.guidang.mapper.GuidangpackageMapper;
import cn.yuanqiao.archive.guidang.service.GuidangService;
import cn.yuanqiao.common.exception.ServiceException;
import cn.yuanqiao.common.utils.DateUtils;
import cn.yuanqiao.common.utils.SnowflakeIdGenerator;
import cn.yuanqiao.common.utils.StringUtils;
import cn.yuanqiao.common.utils.SecurityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service
public class GuidangServiceImpl implements GuidangService {
    private static final Logger logger = LoggerFactory.getLogger(GuidangServiceImpl.class);
    @Autowired
    private ITenantSysConfigService sysConfigService;
    @Autowired
    private YqdaarticulatedMapper yqdaarticulatedMapper;
    @Autowired
    private ArchiveOfOfficialDocument archiveOfOfficialDocument;
    @Autowired
    private TenantCategoryMapper tenantCategoryMapper;
    @Autowired
    private GuidangpackageMapper guidangpackageMapper;
    @Autowired
    private TenantYqdaDocumentMapper tenantYqdaDocumentMapper;

    @Override
    public List<Map<String, Object>> getDsrxx(String msg,String folderId,String bhrId) {
        String tenantCode = SecurityUtils.getTenantCode();
        String sql = Case.valueOf(msg,1).getSql(tenantCode,folderId,bhrId);
        if("".equals(sql)){
            throw new ServiceException("参数有误");
        }
        List<Map<String, Object>> list = yqdaarticulatedMapper.executeSql(sql);
        return list;
    }

    @Override
    public void guiDangTimer(String tenantCode) {
        //SecurityContextHolder.set("tenant_code", tenantCode);
        String guidang_position = sysConfigService.selectConfigByKey("GUIDANG_POSITION");
        if(StringUtils.isEmpty(guidang_position) || "null".equals(guidang_position)){
            throw new ServiceException("租户："+tenantCode+"，归档包路径未配置");
        }
        //SecurityContextHolder.set("tenant_code", tenantCode);
        File file = new File(guidang_position);
        List<Map<String, Object>> maps = yqdaarticulatedMapper.executeSql("select file_name from " + tenantCode + "_GUIDANGPACKAGE where state = 2 and is_del = 0");
        ArrayList<String> list = new ArrayList<>();
        for(int j=0;j<maps.size();j++){
            Map<String, Object> map = maps.get(j);
            String file_name = String.valueOf(map.get("FILE_NAME"));
            list.add(file_name);
        }
        if(file.isDirectory()){
            File[] files = file.listFiles();
            for(int i=0;i<files.length;i++){
                File file1 = files[i];
                String name = file1.getName();
                if(list.contains(name)) continue;
                try {
                    String canonicalPath = file1.getCanonicalPath();
                    if(file1.isFile() && name.endsWith("zip")){
                        String msg = archiveOfOfficialDocument.handle(canonicalPath);
                        String state = "1";
                        if(!"".equals(msg)) state = "2";
                        Long id = SnowflakeIdGenerator.generateId();
                        String sql = "insert into "+tenantCode+"_GUIDANGPACKAGE(PACKAGE_ID,SIZE,FILE_NAME,RECEIVE_TIME,IS_DEL,STATE,REASON,PATH) " +
                                "VALUES("+id+",'"+file1.length()+"','"+file1.getName()+"','"+ DateUtils.getTime() +"',0,"+state+",'"+msg+"','"+canonicalPath+"')";
                        int i1 = tenantCategoryMapper.updateMainTableCol(sql);
                        if(i1>0 && "1".equals(state)){
                            file1.delete();
                        }
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }else{
            throw new ServiceException("租户："+tenantCode+"，归档包路径配置有误");
        }
    }

    @Override
    public List<Guidangpackage> selectA001GuidangpackageList(Guidangpackage a001Guidangpackage)
    {
        return guidangpackageMapper.selectA001GuidangpackageList(a001Guidangpackage);
    }

    @Override
    public int deleteA001GuidangpackageByPackageIds(String[] packageIds)
    {
        Guidangpackage guidangpackage = new Guidangpackage();
        return guidangpackageMapper.deleteA001GuidangpackageByPackageIds(guidangpackage.getTableName(),packageIds);
    }

    @Override
    public TenantYqdaDocument getFilePath(Long folderId, Integer type, Long categoryId) {
        TenantCategory tenantCategory = tenantCategoryMapper.selectTenantCategoryByID(categoryId, new TenantCategory().getTableName());
        TenantYqdaDocument document = tenantYqdaDocumentMapper.getPathByConTableId(folderId, type, tenantCategory.getEfileTableName());
        return document;
    }
}
